//
//  NetworkPath.m
//  freeRide
//
//  Created by HuangSui on 2017/4/4.
//  Copyright © 2017年 SuiXun. All rights reserved.
//

#import "NetworkPath.h"

@implementation NetworkPath
#pragma mark --AF数据请求
+(void)requestWithMethod:(TTGState)type andURLString:(NSString *)URLString andParameters:(NSDictionary*)parameters andView:(UIView *)view RequestSuccess:(RequestSuccess)requestSuccess RequestFailed:(RequestFailed)requestFailed
{
    
    
    
    //判断网络环境，这里网络环境未知
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus==AFNetworkReachabilityStatusUnknown) {
        
    }else{
        //网络环境已获得
        if ([AFNetworkReachabilityManager sharedManager].isReachable) {
            //有网络
        }else{
            UIWindow *sysWindow=[[UIApplication sharedApplication].windows lastObject];
            [self showHUD:@"请确认您的手机网络状态是否连接！" andView:sysWindow];
            return;
        }
    }
    
    
    
    
    
    
    AFURLSessionManager *manager = [NetworkPath URLmanager];
    NSMutableURLRequest *request;
    
    switch (type) {
        case 0:
        {
            request=[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
            
            
            /** 获取系统的UA */
            NSString *sysUA = request.allHTTPHeaderFields[@"User-Agent"];
            NSRange startRange = [sysUA rangeOfString:@"("];
            NSRange endRange = [sysUA rangeOfString:@")"];
            NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
            NSString *phoneInfo = [sysUA substringWithRange:range];
            NSArray *temp=[phoneInfo componentsSeparatedByString:@";"];
//            NSLog(@"什么设备%@设备版本%@设备分辨率倍数%@",temp[0],temp[1],temp[2]);
            if (temp.count) {
                [UDF setObject:temp[0] forKey:@"DeviceModel"];
                [request setValue:temp[0] forHTTPHeaderField:@"DeviceModel"];
            }
            NSString *appversion=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
            NSString *osVersion=[NSString stringWithFormat:@"%@",[UIDevice currentDevice].systemVersion];
            [request setValue:appversion forHTTPHeaderField:@"AppVersion"];
            [request setValue:osVersion forHTTPHeaderField:@"OSVersion"];
            

            if (![NSString isNULLString:APPTOKEN])
            {
              [request setValue:APPTOKEN forHTTPHeaderField:@"X-Auth-Token"];
            }
            
        }
            break;
        case 1:
            //声明获取到的数据格式
            // 个人建议还是自己解析的比较好，有时接口返回的数据不合格会报3840错误，大致是AFN无法解析返回来的数据
            request=[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
            
            break;
        case 2:
            request=[[AFJSONRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
            break;
        default:
            break;
    }
//    //请求开始不允许用户点击
//    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    delegate.window.userInteractionEnabled = NO;
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
//        //请求完毕允许用户点击
//        delegate.window.userInteractionEnabled = YES;
        if (error) {
            LRLog(@"%@",response);
            requestFailed (error);
        } else {
            
            NSHTTPURLResponse *myresponse = (NSHTTPURLResponse *)response;
            NSDictionary *allHeaders = myresponse.allHeaderFields;

            if (allHeaders[@"X-Auth-Token"]) {
                NSString *str=[NSString stringWithFormat:@"%@",allHeaders[@"X-Auth-Token"]];
               [UDF setObject:str forKey:@"token"];
                
            }else
            {
                
            }

//            LRLog(@"response\n%@\nresponseObject\n%@",response,responseObject);
//            LRLog(@"%@",response);
            requestSuccess(response ,responseObject);
        }
    }];
    
    [dataTask resume];
}

+(void)GetRequestWithURL:(NSString *)url andParameters:(NSDictionary *)parameters andView:(UIView *)view RequestSuccess:(void (^)(id responseObject))requestSuccess RequestFailed:(RequestFailed)requestFailed {
    //判断请求参数
    NSArray *dictKeysArray = [parameters allKeys];
    for (int i = 0; i<dictKeysArray.count; i++) {
        NSString *key = dictKeysArray[i];
        NSString *obj =[NSString stringWithFormat:@"%@",[parameters objectForKey:key]];
        if ([NSString isNULLString:obj] ) {
            LRLog(@"请求数据有空参数！");
            return;
        }
    }
    
    //判断网络环境，这里网络环境未知
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus==AFNetworkReachabilityStatusUnknown) {
        
    }else{
        //网络环境已获得
        if ([AFNetworkReachabilityManager sharedManager].isReachable) {
            //有网络
        }else{
            UIWindow *sysWindow=[[UIApplication sharedApplication].windows lastObject];
            [self showHUD:@"请确认您的手机网络状态是否连接！" andView:sysWindow];
            return;
        }
    }
    AFHTTPSessionManager *manager = [NetworkPath HttpManager];
    
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        requestSuccess(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        requestFailed (error);
    }];
}


#pragma mark --AF数据富文本
+(void)AFmultiWithURLString:(NSString *)URLString andParameters:(NSDictionary*)parameters andValueFilePathWithKeyFileName:(NSDictionary *)fileDic RequestSuccess:(RequestSuccess)requestSuccess RequestFailed:(RequestFailed)requestFailed
{
    
    //这个地方修改过AF源码
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        
        
        
        NSArray *dictKeysArray = [fileDic allKeys];
        for (int i = 0; i<dictKeysArray.count; i++) {
            
            NSString *filename = dictKeysArray[i];
            NSString *Netname;
            
            if (dictKeysArray.count==1) {
                Netname = @"file";
            }else if (dictKeysArray.count==2){
                if (i==0) {
                    Netname = @"front.jpg";
                }
                if (i==1) {
                    Netname = @"back.jpg";
                }
            }else{
                Netname = [NSString stringWithFormat:@"file[%d]",i];
            }
            NSString *path =[fileDic objectForKey:filename];
            if (Netname != nil && filename != nil) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:Netname fileName:filename mimeType:@"image/jpeg" error:nil];
            }
        }
    } error:nil];
    if (![NSString isNULLString:APPTOKEN])
    {
        [request setValue:APPTOKEN forHTTPHeaderField:@"X-Auth-Token"];
    }
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      // This is not called back on the main queue.
                      // You are responsible for dispatching to the main queue for UI updates
                      dispatch_async(dispatch_get_main_queue(), ^{
                          //Update the progress view
                          //                          [progressView setProgress:uploadProgress.fractionCompleted];
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          
                          requestFailed (error);
                      } else {
                          NSLog(@"%@",response);
                          NSHTTPURLResponse *myresponse = (NSHTTPURLResponse *)response;
                          NSDictionary *allHeaders = myresponse.allHeaderFields;
                          
                          if (allHeaders[@"X-Auth-Token"]) {
                              NSString *str=[NSString stringWithFormat:@"%@",allHeaders[@"X-Auth-Token"]];
                              [UDF setObject:str forKey:@"token"];
                              
                          }
                          requestSuccess(response ,responseObject);
                      }
                  }];
    
    [uploadTask resume];
}
//导航左边按钮
+(UIButton *)SetNavLeftBtnWithController:(UIViewController *)vc withTitle:(NSString *)Btntext andImageName:(NSString *)imageName
{
    //导航栏左边按钮
    UIButton *leftButton = [[UIButton alloc] init];
    leftButton.titleLabel.font=[UIFont systemFontOfSize:16];
    if (Btntext!=nil) {
        [leftButton setTitle:Btntext forState:UIControlStateNormal];
    }
    
    if (imageName!=nil) {
        [leftButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        [leftButton setImage:[UIImage imageNamed:@"返回白"] forState:UIControlStateSelected];
        leftButton.imageEdgeInsets=UIEdgeInsetsMake(0,0,0,22);
    }
    //控件大小适应文字或图片的大小
//    [leftButton sizeToFit];
    leftButton.bounds = CGRectMake(0, 0, 44, 44);
    [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    vc.navigationItem.leftBarButtonItem = leftBtn;
    return leftButton;
}
//导航右边按钮
+(UIButton *)SetNavRightBtnWithController:(UIViewController *)vc withTitle:(NSString *)Btntext andImageName:(NSString *)imageName
{
    //导航栏右边按钮
    UIButton *rightButton = [[UIButton alloc] init];
    rightButton.titleLabel.font=[UIFont systemFontOfSize:16];
    if (Btntext!=nil) {
        [rightButton setTitle:Btntext forState:UIControlStateNormal];
    }
    
    if (imageName!=nil) {
        [rightButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    //控件大小适应文字或图片的大小
    [rightButton sizeToFit];
    [rightButton setTitleColor:[UIColor colorQ] forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    vc.navigationItem.rightBarButtonItem = rightBtn;
    return rightButton;
}
+ (void)showHUD:(NSString *)text andView:(UIView *)view
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    
    
    hud.mode = MBProgressHUDModeText;
    hud.label.text = NSLocalizedString(text, @"HUD message title");
    hud.bezelView.style=MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.backgroundColor=[UIColor blackColor];
    hud.label.textColor=[UIColor whiteColor];
    // Move to bottm center.
    //    hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
    
    [hud hideAnimated:YES afterDelay:2.f];
    
    
}
#pragma mark 颜色转换为图片

+ (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
#pragma mark 检测数据类型，替换空数据
+ (id)replaceNullData:(id)obj
{
    
    
    
    if ([obj isKindOfClass:[NSDictionary class]])
    {
        
        return [self replaceNullWithDictionary:obj];
    }
    else if ([obj isKindOfClass:[NSArray class]])
    {
        return [self replaceNullWithArray:obj];
    }
    else if ([obj isKindOfClass:[NSNumber class]])
    {
        if ([obj isKindOfClass:[NSNull class]] || obj == nil) {
            obj = @(0);
        }
        return obj;
    }
    else if ([obj isKindOfClass:[NSString class]]) {
        return [self replaceNullValue:obj];
    }
    else
    {
        NSString *str=[NSString stringWithFormat:@"%@",obj];
        return [self replaceNullValue:str];
    }
    //走不到这里应该
    return obj;
}

#pragma mark--处理字典
+ (id)replaceNullWithDictionary:(NSMutableDictionary *)dic
{
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    NSArray *allKey = [dic allKeys];
    for (NSString *key in allKey) {
        
        [tempDic setObject:[self replaceNullData:dic[key]] forKey:key];
    }
    return tempDic;
}

#pragma mark--处理数组
+ (id)replaceNullWithArray:(NSMutableArray *)arr
{
    __block NSMutableArray *tempArr = [NSMutableArray array];
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
     {
         [tempArr addObject:[self replaceNullData:obj]];
     }];
    return tempArr;
}

#pragma mark --处理字符串
+ (NSString *)replaceNullValue: (NSString *)string
{
    NSString * newStr = [NSString stringWithFormat:@"%@",string];
    //Nil ||NULL
    if ([newStr isKindOfClass:[NSNull class]] ||
        newStr == nil ||
        [newStr isEqualToString:@"(null)"]||
        [newStr isEqualToString:@""] ||
        [newStr isEqualToString:@"null"] ||
        [newStr isEqualToString:@"<null>"])
    {
        
        newStr = @"";
    }
    return newStr;
}


+ (NSString *)iphoneType {
    
    
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    
    if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
    
    
    if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
    
    if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
    
    if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
    
    if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";
    
    if ([platform isEqualToString:@"iPad1,1"]) return @"iPad 1G";
    
    if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,3"]) return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,6"]) return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator";
    
    if ([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";
    
    return platform;
    
}
//kvc 获取所有key值
- (NSArray *)getAllIvar:(id)object
{
    NSMutableArray *array = [NSMutableArray array];
    
    unsigned int count;
    Ivar *ivars = class_copyIvarList([object class], &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivars[i];
        const char *keyChar = ivar_getName(ivar);
        NSString *keyStr = [NSString stringWithCString:keyChar encoding:NSUTF8StringEncoding];
        @try {
            id valueStr = [object valueForKey:keyStr];
            NSDictionary *dic = nil;
            if (valueStr) {
                dic = @{keyStr : valueStr};
            } else {
                dic = @{keyStr : @"值为nil"};
            }
            [array addObject:dic];
        }
        @catch (NSException *exception) {}
    }
    return [array copy];
}

//获得所有属性
- (NSArray *)getAllProperty:(id)object
{
    NSMutableArray *array = [NSMutableArray array];
    
    unsigned int count;
    objc_property_t *propertys = class_copyPropertyList([object class], &count);
    for (int i = 0; i < count; i++) {
        objc_property_t property = propertys[i];
        const char *nameChar = property_getName(property);
        NSString *nameStr = [NSString stringWithCString:nameChar encoding:NSUTF8StringEncoding];
        [array addObject:nameStr];
    }
    return [array copy];
}
+(void)leaveVC
{
    
    
//    [JPUSHService setTags:nil alias:@"" fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
//
//        if (iResCode!=0) {
//
//            LRLog(@"极光设置别名失败");
//        }
//    }];
//    EMError *error = [[EMClient sharedClient] logout:YES];
//    if (!error) {
//        NSLog(@"退出成功");
//    }
    
    //清除token
    
    [UDF removeObjectForKey:@"token"];
    [UDF removeObjectForKey:@"cookie"];
    
    [UDF synchronize];
    
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    [appDelegate switchController];
}
+(void)DownloadTask:(NSString *)downLoadUrl
{
    
    AFURLSessionManager *manager = [NetworkPath URLmanager];
    //http://example.com/download.zip
    NSURL *URL = [NSURL URLWithString:downLoadUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);
    }];
    [downloadTask resume];
}
+(void)UploadTask:(NSString *)uploadUrl fromPath:(NSString *)locationPath
{
    
    AFURLSessionManager *manager = [NetworkPath URLmanager];
    //http://example.com/upload
    NSURL *URL = [NSURL URLWithString:uploadUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    //file://path/to/image.png
    NSURL *filePath = [NSURL fileURLWithPath:locationPath];
    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"Success: %@ %@", response, responseObject);
        }
    }];
    [uploadTask resume];
}
+(void)MultiPartRequest:(NSString *)URLString andParameters:(NSDictionary*)parameters andValueFilePathWithKeyFileName:(NSDictionary *)fileDic RequestSuccess:(RequestSuccess)requestSuccess RequestFailed:(RequestFailed)requestFailed
{
    //file,filename.jpg,image/jpeg,POST写死了
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSArray *dictKeysArray = [fileDic allKeys];
        for (int i = 0; i<dictKeysArray.count; i++) {
            
            NSString *filename = dictKeysArray[i];
            NSString *path =[fileDic objectForKey:filename];
            NSString *Netname;
            Netname = [NSString stringWithFormat:@"file[%d]",i];

        [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
        }
    } error:nil];
    if (![NSString isNULLString:COOKIE])
    {
        [request setValue:COOKIE forHTTPHeaderField:@"X-Auth-Token"];
    }
    AFURLSessionManager *manager = [NetworkPath URLmanager];
    
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      dispatch_async(dispatch_get_main_queue(), ^{
//    [progressView setProgress:uploadProgress.fractionCompleted];
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          requestFailed (error);
                      } else {
                          NSHTTPURLResponse *myresponse = (NSHTTPURLResponse *)response;
                          NSDictionary *allHeaders = myresponse.allHeaderFields;
                          
                          if (allHeaders[@"X-Auth-Token"]) {
                              NSString *str=[NSString stringWithFormat:@"%@",allHeaders[@"X-Auth-Token"]];
                              [UDF setObject:str forKey:@"cookie"];
                              
                          }
                          requestSuccess(response ,responseObject);
                      }
                  }];
    
    [uploadTask resume];
}

+(void)requestWithMethod:(TTGState)type andURLString:(NSString *)URL andParameters:(NSDictionary*)parameters RequestSuccess:(RequestSuccess)requestSuccess RequestFailed:(RequestFailed)requestFailed
{
    NSString *URLString = [NSString stringWithFormat:@"%@%@",APPBaseUrl,URL];
    AFURLSessionManager *manager = [NetworkPath URLmanager];
    NSMutableURLRequest *request;
    switch (type) {
        case 0:
            //原始数据
            request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
            break;
        case 1:
            //原始数据
            request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
            break;
        case 2:
            //参数序列化
            request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
            break;
            
        default:
            break;
    }
    if (![NSString isNULLString:COOKIE])
    {
        [request setValue:COOKIE forHTTPHeaderField:@"X-Auth-Token"];
    }
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            requestFailed (error);
        } else {
            
            NSHTTPURLResponse *myresponse = (NSHTTPURLResponse *)response;
            NSDictionary *allHeaders = myresponse.allHeaderFields;
            
            if (allHeaders[@"X-Auth-Token"]) {
                NSString *str=[NSString stringWithFormat:@"%@",allHeaders[@"X-Auth-Token"]];
                [UDF setObject:str forKey:@"cookie"];
                
            }
            requestSuccess(response ,responseObject);
        }
    }];
    [dataTask resume];
    
    
    
    
    //示例
    /*
     NSString *URLString = @"/axq/admin/users";
     NSDictionary *parameters = @{@"peopletel": @""};
     [NetworkPath requestWithMethod:0 andURLString:URLString andParameters:parameters RequestSuccess:^(NSURLResponse *response, id responseObject) {
     NSLog(@"%@",responseObject);
     NSString *code=[NetworkPath getValue:@"code" from:responseObject];
     if (code.length) {
     if([code isEqualToString:@"10008"])
     {
     
     }else
     {
     NSString *str=[NetworkPath getValue:@"msg" from:responseObject];
     
     [self.view makeToast:str];
     }
     }
     
     } RequestFailed:^(NSError *error) {
     
     }];
    */
    
//    /axq/admin/{uid} （没有用到这个接口）
//    /axq/admin/users（参数查询没有用）
    
}
+ (AFURLSessionManager*)URLmanager{
    static dispatch_once_t onceToken;
    static AFURLSessionManager *manager = nil;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfiguration];
    });
    return manager;
}
//设置https
+(AFHTTPSessionManager *)HTTPManager
{
    static dispatch_once_t onceToken;
    static AFHTTPSessionManager *manager = nil;
    dispatch_once(&onceToken, ^{
        //https
        manager = [AFHTTPSessionManager manager];
        // not recommended for production
        manager.securityPolicy.allowInvalidCertificates = YES;
    });
    return manager;
}
+(AFHTTPSessionManager *)HttpManager {
    static dispatch_once_t onceToken;
    static AFHTTPSessionManager *manager = nil;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:sessionConfiguration];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    });
    
    return manager;
}
+(NSString *)getValue:(NSString *)key from:(id)object
{
    //1.先判断responseObject是不是字典
    if ([object isKindOfClass:[NSDictionary class]]) {
        //2.再判断字典有没有code key
        if (object[key]) {
            //3. code转化为字符串 防止类型崩溃
            NSString *code = [NSString stringWithFormat:@"%@",object[key]];
            return code;
        }
    }
    return @"";
}
+(BOOL)isDictionary:(NSString *)key from:(id)object
{
    if ([object isKindOfClass:[NSDictionary class]])
    {
        if (object[key]) {
            if ([object[key] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic=object[key];
                if (dic.count) {
                    
                    return YES;
                }
            }
        }
    }
    return NO;
}
+(BOOL)isNSArray:(NSString *)key from:(id)object
{
  if ([object isKindOfClass:[NSDictionary class]])
  {
     if (object[key])
     {
         if ([object[key] isKindOfClass:[NSArray class]]) {
             NSArray *arr=object[key];
             if (arr.count) {
                 return YES;
             }
         }
     }
  }
    return NO;
}






@end
